package net.toby200.canalbuddy.notices.gcm;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.json.gson.GsonFactory;

import net.toby200.canalbuddy.R;
import net.toby200.canalbuddy.notices.MainActivity;
import net.toby200.canalstoppages.stoppages.Stoppages;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by toby on 31/07/2014.
 */
public class GcmRegistrar extends AsyncTask<Void, Void, String> {
    private static final Logger LOG = Logger.getLogger(GcmRegistrar.class.getName());

    private final Context context;
    private final MainActivity activity;

    public GcmRegistrar(MainActivity activity) {
        this.activity = activity;
        this.context = activity.getApplicationContext();
    }

    public String getRegId() {
        return activity.getPreferences(Context.MODE_PRIVATE).getString(context.getString(R.string.regid_pref_key), null);
    }

    @Override
    protected String doInBackground(Void... params) {
        String regId = null;
        try {
            GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
            String projectNum = context.getString(R.string.gcmProjectNumber);
            regId = gcm.register(projectNum);

            if (regId != null) {
                // save regId in prefs, and register it with the backend
                saveRegId(regId);
            }

        } catch (IOException e) {
            LOG.log(Level.WARNING, "Unable to register for notifications", e);
        }
        return regId;

    }

    private void saveRegId(String regId) {
        LOG.info("Device registered, registration ID=" + regId);

        SharedPreferences.Editor editor = activity.getPreferences(Context.MODE_PRIVATE).edit();
        editor.putString(context.getString(R.string.regid_pref_key), regId);
        editor.commit();
        registerDeviceWithBackend(regId);


    }

    private void registerDeviceWithBackend(String regId) {
        // register with our app-engine backend
        try {
            Stoppages.Builder builder = new Stoppages.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), null);
            builder.setApplicationName("CanalBuddyClient");
            Stoppages service = builder.build();
            service.registerId(regId).execute();
        } catch (Exception e) {
            LOG.log(Level.SEVERE, "Failed to register device id with backend", e);
        }
    }

    @Override
    protected void onPostExecute(String regId) {
        activity.setGCMRegId(regId);
    }


}
